﻿using Microsoft.AspNetCore.Authorization.Infrastructure;
using Microsoft.AspNetCore.Authorization;
using ResourceBasedAuthApp.Data;

namespace ResourceBasedAuthApp.Services
{
    #region snippet_Handler
    public class DocumentAuthorizationCrudHandler : AuthorizationHandler<OperationAuthorizationRequirement, DocumentEntity>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, OperationAuthorizationRequirement requirement, DocumentEntity resource)
        {
            var claim = context.User.Claims.FirstOrDefault(c => c.Type == "userName");
            if (claim.Value == resource.Editor &&
                requirement.Name == Operations.Read.Name)
            {
                context.Succeed(requirement);
            }

            return Task.CompletedTask;
        }
    }
    #endregion

    #region snippet_OperationsClass
    public static class Operations
    {
        public static OperationAuthorizationRequirement Create =
            new OperationAuthorizationRequirement { Name = nameof(Create) };
        public static OperationAuthorizationRequirement Read =
            new OperationAuthorizationRequirement { Name = nameof(Read) };
        public static OperationAuthorizationRequirement Update =
            new OperationAuthorizationRequirement { Name = nameof(Update) };
        public static OperationAuthorizationRequirement Delete =
            new OperationAuthorizationRequirement { Name = nameof(Delete) };
    }
    #endregion
}
